<template>
  <div class="create-post-container">
    <el-form ref="postForm" :model="postForm" :rules="rules" label-position="right" label-width="100px" class="category-form">
      <el-row :gutter="20">
        <el-col :span="18" :offset="3">
          <el-form-item label="名称" prop="name">
            <el-input v-model="postForm.name" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="9" :offset="3">
          <el-form-item label="所属群组" prop="clusterId">
            <el-select
              v-model="postForm.clusterId"
              multiple
              placeholder="可多选"
              style="width:100%"
            >
              <el-option
                v-for="item in clusterOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="9">
          <el-form-item label="CODE" prop="code">
            <el-input v-model="postForm.code" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="9" :offset="3">
          <el-form-item label="类型" prop="typeid">
            <el-select
              v-model="postForm.typeid"
              placeholder="请选择类型"
              style="width:100%"
            >
              <el-option
                v-for="item in typeOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="上级分类" prop="superior">
            <el-select
              v-model="postForm.superior"
              placeholder="请选择上级分类"
              style="width:100%"
            >
              <el-option
                v-for="item in superiorOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="18" :offset="3">
          <el-form-item label="上传图标" prop="icon">
            <el-upload
              v-if="iconList < 1"
              :action="uploadUrl"
              :multiple="false"
              :limit="1"
              name="fies"
              :headers="{token}"
              :on-success="handleUploadSucc"
              :show-file-list="false"
              drag
              accept="image/jpeg,image/png,image/gif"
              class="drag-upload-wrapper"
            >
              <i class="el-icon-upload" />
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            </el-upload>

            <ul v-else class="thumb-img-list">
              <li
                v-for="(item, index) in iconList"
                :key="index"
                class="item"
              >
                <img :src="item.url" :alt="item.name" class="img">
                <div
                  class="el-icon-close close-btn"
                  title="点击可删除"
                  @click="handleUploadRemove(item)"
                />
              </li>
            </ul>
            <!-- <input v-model="postForm.icon" type="hidden"> -->
          </el-form-item>

        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="18" :offset="3">
          <el-form-item label="是否上线" prop="online">
            <el-switch v-model="postForm.online" :active-value="1" :inactive-value="0" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20" class="mt30">
        <el-col :span="18" :offset="3">
          <el-form-item>
            <el-button type="primary" @click="submitForm">提 交</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import {
  getCategories,
  addCategory,
  updateCategory
} from '@/api/articles'
import {
  getArticleTypes,
  getArticleSuperior,
  getAllCluster
} from '@/api/baseData'

const defaultForm = {
  id: undefined,
  name: '',
  clusterId: [],
  code: '',
  typeid: '',
  superior: '',
  icon: '',
  online: 0
}

export default {
  name: 'ArticlesCategoryForm',
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      clusterOptions: [],
      typeOptions: [],
      superiorOptions: [],
      iconList: [],
      postForm: Object.assign({}, defaultForm),
      loading: false,
      rules: {
        name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字', trigger: 'blur' }
        ],
        clusterId: [
          { required: true, message: '请选择所属群组', trigger: 'change' }
        ],
        // code: [
        //   { required: true, message: '请输入CODE', trigger: 'blur' }
        // ],
        typeid: [
          { required: true, message: '请选择类型', trigger: 'change' }
        ]
        // superior: [
        //   { required: true, message: '请选择上级分类', trigger: 'change' }
        // ]
        // icon: [
        //   { required: true, message: '请上传图标', trigger: 'change' }
        // ]
      },
      uploadUrl: process.env.VUE_APP_BASE_API + '/content/imgUpload'
    }
  },
  computed: {
    ...mapGetters([
      'token'
    ])
  },
  created() {
    this.fetchClusterList()
    this.fetchArticleTypes()
    this.fetchArticleSuperior()
    if (this.isEdit) {
      const id = this.$route.params && this.$route.params.id
      this.fetchData(id)
    }
  },
  methods: {
    fetchClusterList() {
      getAllCluster().then(response => {
        // console.log(response)
        this.clusterOptions = response.data
      }).catch(err => {
        console.log(err)
      })
    },
    fetchArticleTypes() {
      getArticleTypes().then(response => {
        this.typeOptions = response.data
      }).catch(err => {
        console.log(err)
      })
    },
    fetchArticleSuperior() {
      getArticleSuperior().then(response => {
        this.superiorOptions = response.data
      }).catch(err => {
        console.log(err)
      })
    },
    fetchData(id) {
      getCategories({ id }).then(response => {
        const { data } = response
        console.log(data)
        this.iconList.push({
          name: 'uploadIcon',
          url: data[0].icon
        })
        this.postForm.id = data[0].id
        this.postForm.name = data[0].name
        this.postForm.clusterId = data[0].clusterId
        this.postForm.code = data[0].code
        this.postForm.typeid = data[0].typeid
        this.postForm.superior = data[0].superior
        this.postForm.icon = data[0].icon
        this.postForm.online = data[0].online
      }).catch(err => {
        console.log(err)
      })
    },
    handleUploadRemove(file) {
      // console.log(file)
      // this._.remove(this.iconList, function(img) {
      //   return img.url === file.url
      // })
      // if (this.postForm.icon === file.url) {
      //   this.postForm.icon = ''
      // }
      // console.log(this.postForm.icon)
      // console.log(this.iconList)

      const index = this.iconList.indexOf(file)
      if (index !== -1) {
        this.iconList.splice(index, 1)
        this.postForm.icon = ''
      }
    },
    handleUploadSucc(res) {
      // console.log(res)
      const url = res.data[0]
      this.postForm.icon = url
      this.iconList.push({
        name: 'uploadIcon',
        url: url
      })
      // console.log(this.postForm.icon)
    },
    submitForm() {
      this.$refs.postForm.validate(valid => {
        if (valid) {
          // this.postForm.icon = this.postForm.icon.join(',')
          this.postForm.clusterId = this.postForm.clusterId.join(',')
          console.log(this.postForm)

          this.loading = true
          if (this.isEdit) {
            updateCategory(this.postForm).then(response => {
              // console.log(response)
              this.$notify({
                title: '成功',
                message: '编辑文章分类成功',
                type: 'success',
                duration: 2000
              })
              this.loading = false
              this.$router.go(-1)
            }).catch(err => {
              console.log(err)
            })
          } else {
            addCategory(this.postForm).then(response => {
              // console.log(response)
              this.$notify({
                title: '成功',
                message: '添加文章分类成功',
                type: 'success',
                duration: 2000
              })
              this.loading = false
              this.$router.go(-1)
            }).catch(err => {
              console.log(err)
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm() {
      this.$refs.postForm.resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
.create-post-container {
  position: relative;
  .category-form {
    padding: 40px;
  }
}
</style>
